#include "jarvisapp.h"

JarvisAPP::JarvisAPP()
{
    m_type = Type::OTHER;
}

void JarvisAPP::Init(QString resPath)
{
    apps = getApplications();
}

QWidget *JarvisAPP::GetWidget(QWidget *parent)
{
    return nullptr;
}

void JarvisAPP::PollMessage(JarvisInterface::Type from, QJsonObject data)
{
    if(from == Type::SPEECH){
        if(data["MODE"] == "AIUI"){
            data = data["data"].toObject()["data"].toArray()[0].toObject();
            QString service = data["intent"].toObject()["service"].toString();
            if(service == "app"){
                QString ret = data["intent"].toObject()["semantic"].toArray()[0].toObject()["slots"].toArray()[0].toObject()["value"].toString();
                //root = root["intent"]["semantic"][0]["slots"][0]["value"];
                if(apps.contains(ret))openAPP(apps[ret]);
            }
        }
    }
}

JarvisAPP::~JarvisAPP()
{

}
#ifdef Q_OS_ANDROID
void JarvisAPP::openAPP(QString packName)
{
    //android.content.pm.PackageManager
    QAndroidJniObject action = QAndroidJniObject::fromString(packName);
    QAndroidJniObject intent = manager.callObjectMethod("getLaunchIntentForPackage","(Ljava/lang/String;)Landroid/content/Intent;",action.object<jstring>());
    if(intent.isValid())QtAndroid::startActivity(intent, 0);
}
#else
void JarvisAPP::openAPP(QString packName){
    QProcess *tmp = new QProcess();
    tmp->start(packName);
}
#endif

#ifdef Q_OS_ANDROID
QMap<QString, QString> JarvisAPP::getApplications()
{
    QMap<QString,QString> ret;
    QAndroidJniObject packs = manager.callObjectMethod("getInstalledPackages","(I)Ljava/util/List;",0);
    jint cnt = packs.callMethod<jint>("size","()I");
    for (int i=0;i<cnt;++i) {
        QAndroidJniObject info = packs.callObjectMethod("get","(I)Ljava/lang/Object;",i);
        QString packname = info.getObjectField<jstring>("packageName").toString();
        //packageInfo.applicationInfo.loadLabel(getPackageManager()).toString()
        QAndroidJniObject subinfo = info.getObjectField("applicationInfo","Landroid/content/pm/ApplicationInfo;");
        QString name = subinfo.callObjectMethod("loadLabel","(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;",manager.object()).toString();
        ret[name] = packname;
    }
    return ret;
}
#else
QMap<QString, QString> JarvisAPP::getApplications(){
    QMap<QString,QString> ret;
    ret["网易云音乐"] = "netease-cloud-music";
    return ret;
}
#endif
